#coding=utf-8
#python3.6
import pygame,sys
from pygame.locals import * #常用函数和常量
from pygame import draw


background_image_filename = r'image/background.png' #背景图
mouse_cursor_filename = r'image/cat.png' #鼠标光标图
mouse_image_filename = r'image/mouse.png' #鼠标光标图
ROLE1_IMG_CATALOGUE_PATH = r'image/MT_housemaid/' #角色1图片目录路径

UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'
FPS = 30 # 帧率
SCREEN_WIDTH, SCREEN_HEIGHT= 800,600 # 窗口宽、高
RECT_WIDTH,RECT_HEIGHT = 120,120 # 目标矩形宽高
RECT_X,RECT_Y = 10,10 # 目标矩形初始坐标（左上角）
PLAYER_COUNT = 1 # 玩家数量
RECT_PREFACTORING = pygame.Rect(RECT_X,RECT_Y,RECT_WIDTH,RECT_HEIGHT) #预定义矩形位置和大小
INVERSION_ACTION_MODE = {UP:DOWN, DOWN:UP, LEFT:RIGHT ,RIGHT:LEFT } # 反转行动方向方式
INVERSION_TURN_MODE = {UP:RIGHT, DOWN:LEFT, LEFT:UP, RIGHT:DOWN} # 反转转角方向方式

# 定义玩家操控的角色动作资源总字典,简称 玩家字典
PLAYER_RESOURCE_DICT = {}
for player_number in range(1,PLAYER_COUNT+1):
    # 排好玩家编号，赋值上动作资源字典
    PLAYER_RESOURCE_DICT['player'+str(player_number)] = {UP:[],DOWN:[],LEFT:[],RIGHT:[]}


def main():
    action_orientation = RIGHT  # 行动方向 初始化
    last_action_orientation = ''  # 上一次行动方向
    mouse_x, mouse_y = 0, 0  # 鼠标事件时的坐标
    inversion_status = False  # 是否反向
    already_inversion_status = False  # 是否已经反向
    mouse_down_status = False  # 鼠标是否按下
    player1_Now_show_surface = '' # 玩家1控制的角色当前显示图片，加载对象
    action_change_velocity = 4 # 角色动作转换速率，相当于游戏循环4次才改变一次
    assert action_change_velocity % 3 == 1 # 角色动作转换速率必须是3的倍数 + 1
    action_loop_time = 0 #当前动作循环次数

    # 初始化pygame,为使用硬件做准备
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)  # 创建游戏窗口
    pygame.display.set_caption("Hello, World!")  # 设置窗口名称
    fpsClock = pygame.time.Clock()  # 时钟对象，控制运行速率
    # 加载并转化图像
    background_img = pygame.image.load(background_image_filename).convert() #背景
    mouse_cursor = pygame.image.load(mouse_cursor_filename).convert_alpha() #光标
    for player_number in PLAYER_RESOURCE_DICT: # 遍历玩家字典 键（玩家名称）
        for orientation in INVERSION_ACTION_MODE: # 4个方向
            for img_number in range(1,4): # 每个方向3个图片
                action_surface = pygame.image.load(ROLE1_IMG_CATALOGUE_PATH + orientation + '_' + str(img_number) + '.png').convert_alpha()
                PLAYER_RESOURCE_DICT[player_number][orientation].append(action_surface) # 填充 玩家字典

    while True:
        # 主循环
        for event in pygame.event.get():
            if event.type == QUIT:
                # 接收到退出事件后退出程序
                sys.exit()
            if event.type == MOUSEBUTTONDOWN:
                mouse_x,mouse_y = event.pos
                mouse_down_status = True

        # 将背景图画上去
        # screen.blit(background_img, (0, 0))
        screen.fill((0,0,0))
        # 判断当前位置是否需要转弯
        turn_orientation = ''
        if RECT_PREFACTORING.right == SCREEN_WIDTH - RECT_X and RECT_PREFACTORING.top == RECT_Y:
            turn_orientation = DOWN  # 走到自定的右上边界时，停止向右，开始向下
        elif RECT_PREFACTORING.right == SCREEN_WIDTH - RECT_X and RECT_PREFACTORING.top == SCREEN_HEIGHT - RECT_WIDTH - RECT_Y:
            turn_orientation = LEFT  # 走到自定的右下边界时，停止向下，开始向左
        elif RECT_PREFACTORING.right == RECT_WIDTH + RECT_X and RECT_PREFACTORING.top == SCREEN_HEIGHT - RECT_WIDTH - RECT_Y:
            turn_orientation = UP  # 走到自定的左下边界时，停止向左，开始向上
        elif RECT_PREFACTORING.right == RECT_WIDTH + RECT_X and RECT_PREFACTORING.top == RECT_Y:
            turn_orientation = RIGHT  # 走到自定的左上边界时，停止向上，开始向右

        # 最终判断行动方向
        if inversion_status is True: # 当反向状态时
            if turn_orientation != '':  # 转角时，向左走（逆时针）
                action_orientation = INVERSION_TURN_MODE[turn_orientation]
            elif already_inversion_status is False:  # 行走时， 反转行走方向
                action_orientation = INVERSION_ACTION_MODE[action_orientation]
                already_inversion_status = True  # 设置为反向中，下次循环就不会再反转行走方向，导致原地卡动
        else: # 正常行动
            if turn_orientation != '':  # 转角时，向右走（顺时针）
                print('转角')
                action_orientation = turn_orientation
            # 行走时，顺时针（左边界向上，右下，上右，下左）
            elif RECT_PREFACTORING.right == RECT_WIDTH + RECT_X:
                action_orientation = UP
            elif RECT_PREFACTORING.right == SCREEN_WIDTH - RECT_X:
                action_orientation = DOWN
            elif RECT_PREFACTORING.top == RECT_Y:
                action_orientation = RIGHT
            elif RECT_PREFACTORING.top == SCREEN_HEIGHT - RECT_Y - RECT_PREFACTORING.height:
                action_orientation = LEFT
        # 当行动方向改变时，打印改变的行动方向
        if action_orientation != last_action_orientation and last_action_orientation != '':
            msg = '行动方向:'
            if inversion_status is True:
                msg = '（反）' + msg
            print(msg,action_orientation,'反向',inversion_status,'反向中:',already_inversion_status)

        # 移动目标物坐标
        if action_orientation == RIGHT:  # 开关开启时向右移动10像素
            # print('向右走')
            RECT_PREFACTORING.right += 10
        elif action_orientation == LEFT:
            # print('向左走')
            RECT_PREFACTORING.right -= 10
        elif action_orientation == UP:
            # print('向上走')
            RECT_PREFACTORING.top -= 10
        else:
            assert action_orientation == DOWN
            # print('向下走')
            RECT_PREFACTORING.top += 10

        # 绘制 玩家1
        if action_loop_time == action_change_velocity or player1_Now_show_surface == '': #每循环规定次数，才改变动作
            action_loop_time = 0
            if action_orientation in [UP,DOWN]:
                orientation_list_index = RECT_PREFACTORING.top % 3 #确定当前方向行动图片编号
                player1_Now_show_surface = PLAYER_RESOURCE_DICT['player1'][action_orientation][orientation_list_index]
            elif action_orientation in [LEFT,RIGHT]:
                orientation_list_index = RECT_PREFACTORING.left % 3
                player1_Now_show_surface = PLAYER_RESOURCE_DICT['player1'][action_orientation][orientation_list_index]
        action_loop_time += 1
        target_rect = draw.rect(screen, (0, 0, 0, 0), RECT_PREFACTORING, 0)  # 这个矩形用于点击事件
        screen.blit(player1_Now_show_surface, (RECT_PREFACTORING.left, RECT_PREFACTORING.top))

        # 判断反向状态
        whether_at = target_rect.collidepoint(mouse_x, mouse_y)  # 判断坐标位置是否在目标物范围内
        if whether_at == 1 and mouse_down_status is True: # 鼠标在矩形内并被 放开
            print('点上了')
            # 改变反向状态（正常状态下变成反向状态，反向变正常）
            if inversion_status == True:
                inversion_status = False
            else:
                inversion_status = True
            already_inversion_status = False #初始 已经反向状态 为否

        mouse_down_status = False # 初始化 鼠标放开状态
        last_action_orientation = action_orientation # 行动之后，才赋值给 上次行动方向变量 last_action_orientation

        # 获得鼠标位置
        x, y = pygame.mouse.get_pos()

        # 计算光标的左上角位置
        x -= mouse_cursor.get_width() / 2
        y -= mouse_cursor.get_height() / 2

        # 把光标画上去
        screen.blit(mouse_cursor, (x, y))

        # 刷新一下画面
        pygame.display.update()
        fpsClock.tick(FPS)

if __name__ == '__main__':
    main()